package com.qw.flutter.thirdlogin.wxapi;

import android.content.Context;

import androidx.annotation.Nullable;

import com.qw.flutter.thirdlogin.R;
import com.qw.flutter.thirdlogin.util.LogUtils;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel.Result;


/**
 * @date: 2021/5/14 13:51
 * @author: lixu
 * @description: 微信相关封装
 */
public class WechatWrapper {
    private static final String TAG = "WechatLoginWrapper";
    private IWXAPI api;
    private static Result result;

    public static WechatWrapper create(Context context, String appId) {
        LogUtils.d(TAG, "WechatAppID:" + appId);
        return new WechatWrapper(context, appId);
    }

    private WechatWrapper(Context context, String appId) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        this.api = WXAPIFactory.createWXAPI(context.getApplicationContext(), appId, true);
        // 将应用的appId注册到微信
        this.api.registerApp(appId);
    }

    /**
     * 是否安装了微信客户端
     *
     * @return
     */
    private boolean isWXAppInstalled(Context context) {
        return api.isWXAppInstalled();
    }

    /**
     * 调用微信授权登录
     *
     * @param scope 应用授权作用域，如获取用户个人信息则填写 snsapi_userinfo
     * @param state 用于保持请求和回调的状态，授权请求后原样带回给第三方。该参数可用于防止 csrf 攻击（跨站请求伪造攻击），
     *              建议第三方带上该参数，可设置为简单的随机数加 session 进行校验
     */
    public void startWechatLoginAuth(Context context, String scope, @Nullable String state, Result mResult) {
        result = mResult;
        if (!isWXAppInstalled(context)) {
            Map<String, Object> params = new HashMap<>(3);
            params.put("isSuccess", false);
            params.put("msg", context.getString(R.string.no_install_client_tips));
            result.success(params);
            result = null;
        } else {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = scope;
            if (state != null) {
                req.state = state;
            }
            api.sendReq(req);
        }
    }

    /**
     * 授权结果
     *
     * @param isSuccess 是否授权成功
     * @param code      授权code（可为空）
     * @param msg
     */
    public static void setAuthResult(boolean isSuccess, String code, String msg) {
        if (result != null) {
            Map<String, Object> params = new HashMap<>(3);
            params.put("isSuccess", isSuccess);
            params.put("code", code);
            params.put("msg", msg);
            result.success(params);
            result = null;
        }
    }
}
